/*
All credits for the implementation of this class goes to developer.android.com
Small changes has been made to the original found on URL (date 2012-04-04):
http://developer.android.com/guide/topics/location/obtaining-user-location.html
*/

package emt.friendtracking.locationmodule;

import android.location.Location;

public class LocationChecker
{
	private static final int ONE_MINUTES = 1000 * 60;
	
	protected static boolean newLocationIsBetter(Location currentLocation, Location location)
	{
		if (currentLocation == null)
	        return true;

		// Check whether the new location fix is newer or older
	    long deltaTime = location.getTime() - currentLocation.getTime();
	    boolean isSignificantlyNewer = deltaTime > ONE_MINUTES;
	    boolean isSignificantlyOlder = deltaTime < -ONE_MINUTES;
	    boolean isNewer = deltaTime > 0;

	    if (isSignificantlyNewer)
	        return true;
	    else if (isSignificantlyOlder)
	        return false;

	    // Check whether the new location fix is more or less accurate
	    int deltaAccuracy = (int) (location.getAccuracy() - currentLocation.getAccuracy());
	    boolean isLessAccurate = deltaAccuracy > 0;
	    boolean isMoreAccurate = deltaAccuracy < 0;
	    boolean isSignificantlyLessAccurate = deltaAccuracy > 100;

	    // Check if the old and new location are from the same provider
	    boolean isFromSameProvider = isSameProvider(location.getProvider(), currentLocation.getProvider());

	    // Determine location quality using a combination of timeliness and accuracy
	    if (isMoreAccurate)
	        return true;
	    else if (isNewer && !isLessAccurate)
	        return true;
	    else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider)
	        return true;
	    
	    return false;
	}
	
	private static boolean isSameProvider(String providerNewLocation, String providerCurrentLocation)
	{
	    if (providerNewLocation == null)
	      return providerCurrentLocation == null;
	    
	    return providerNewLocation.equals(providerCurrentLocation);
	}
}
